//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Form, Input, message, Modal, Select } from "antd";
import { useSeaOtterStores } from "../store";
import { get_session } from "@/api/user";
import { request } from "@/utils/request";
import { gen_access_token } from "@/api/project_server";
import type { WatchInfo } from "@/api/seaotter/watch";
import { create as create_watch, update as update_watch } from "@/api/seaotter/watch";
import type { ImageInfo } from "@/api/seaotter/image";
import { list_all_image } from "@/api/seaotter/image";


interface EditWatchModalProps {
    watchInfo?: WatchInfo;
    onCancel: () => void;
    onOk: () => void;
}

const EditWatchModal = (props: EditWatchModalProps) => {
    const appStore = useSeaOtterStores();

    const [fullImageNameList, setFullImageNameList] = useState<string[]>(props.watchInfo?.full_image_name_list ?? []);
    const [desc, setDesc] = useState(props.watchInfo?.desc ?? "");
    const [hasChange, setHasChange] = useState(false);
    const [imageList, setImageList] = useState<ImageInfo[]>([]);

    const loadImageList = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        const listRes = await request(list_all_image(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
        }));
        setImageList(listRes.image_list);
    };

    const createWatch = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        await request(create_watch(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            full_image_name_list: fullImageNameList,
            desc: desc,
        }));
        message.info("创建成功");
        props.onOk();
    };

    const updateWatch = async () => {
        if (props.watchInfo == undefined) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        await request(update_watch(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            watch_id: props.watchInfo.watch_id,
            full_image_name_list: fullImageNameList,
            desc: desc,
        }));

        message.info("更新成功");
        props.onOk();
    };

    useEffect(() => {
        loadImageList();
    }, []);

    return (
        <Modal open title={props.watchInfo == undefined ? "创建变更通知配置" : "更新变更通知配置"} mask={false}
            okText={props.watchInfo == undefined ? "创建" : "更新"} okButtonProps={{ disabled: !(fullImageNameList.length > 0 && hasChange) }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (props.watchInfo == undefined) {
                    createWatch();
                } else {
                    updateWatch();
                }
            }}>
            <Form labelCol={{ span: 3 }}>
                <Form.Item label="相关镜像">
                    <Select mode="multiple" value={fullImageNameList} onChange={values => {
                        setFullImageNameList(values);
                        setHasChange(true);
                    }}>
                        {imageList.map(imageInfo => (
                            <Select.Option key={`${imageInfo.group_name}/${imageInfo.image_name}`} value={`${imageInfo.group_name}/${imageInfo.image_name}`}>
                                {imageInfo.group_name}/{imageInfo.image_name}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="备注">
                    <Input value={desc} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setDesc(e.target.value);
                        setHasChange(true);
                    }} />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default observer(EditWatchModal);